<template>
  <div class="shuoshuo-container">
    <ylheader :leftsvg="true" :title="'说说'" :rightsvg="true" :addsvg="true" @adds="addshuoshuo" @search="sayssearch"></ylheader>
    <mt-navbar :class="'shuoshuo-mtnav'" v-model="selected" fixed style="margin-top: 0.88rem">
      <mt-tab-item @click.native="saynew()" id="1">最新</mt-tab-item>
      <mt-tab-item @click.native="sayhot()" id="2">最热</mt-tab-item>
    </mt-navbar>
    <div class="shuoshuo-navbar-sep"></div>
    <versioncofig
    :versionTitle="ruleConfig.saysRuleTitle"
    @toVersionDetail="$router.push({name:'activityrule',query:{tag:6}, params:{saysRuleContent:ruleConfig.saysRuleContent}})"
    @canclVersion="isRuleShow=!isRuleShow"
    v-if="isRuleShow"
    ></versioncofig>
    <mt-tab-container v-model="selected" :style="{'margin-top':isRuleShow?'1.50rem':'0.8rem'}">
      <div v-if="selected==myid">
        <div class="shuoshuo-new" v-if="isshuoshuoempty">
        <span class="yl-2kong nosvg">
            <span class="path1">
              <span class="path2">
                <span class="path3">
                  <span class="path4">
                    <span class="path5">
                      <span class="path6">
                        <span class="path7">
                          <span class="path8">
                            <span class="path9"></span>
                          </span>
                        </span>
                      </span>
                    </span>
                  </span>
                </span>
              </span> 
            </span>
        </span>
          <span class="no-text">啊哦，这里空空的，让人感觉怪怪的，赶紧来填上一笔吧！</span>
        </div>
        <div class="hot-shuohsuo loadmore-container" ref="sayWrapper">
          <ul class="loadmore-ul" ref="wrapperUl">
            <li style="background-color: white;margin-bottom: .2rem" v-for="(item,index) in commentlist" :key="index">
              <hotheader :commentindex="index" :type="1" :nickname="item.name" :saytime="item.timeStamp" :avatarimg="item.head" @topiccommentdetail="tosaycomdet" :place="item.place" :userType="item.userType" :isTalent="item.isTalent" :pendantType="item.pendantType" :pendantPicUrl="item.pendantPicUrl"></hotheader>
              <commentbody :commentindex="index" :commenttype="null" @replycomment="tosaycomdet" :commenttext="item.content" :piclength="item.picture.length" :picarray="item.picture" @showImg="popupImg"></commentbody>
              <thubm-up :topiccommentnum="item.commentNumber" :thumbupnum="item.likes" :commentindex="index" :isup="item.isgood" @thumbup="saythumbup" @commentsvgg="saycomment"></thubm-up>
            </li>
          </ul>
        </div>
      </div>
    </mt-tab-container>
    <transition name="fade">
      <div class="modal-img" v-if="popupVisible" @click="popupVisible=false">
        <mt-swipe :auto="100000" style="width: 100%;height: 100vh;position:relative;"
        :continuous="false" 
          :defaultIndex="swiperIndex" :showIndicators="false" >
            <mt-swipe-item v-for="(item,index) in popImg" :key="index" style="height:100vh" >
              <img v-lazy="item" class="swiper-img" />
            </mt-swipe-item>
          </mt-swipe>
      </div>
    </transition>
  </div>
</template>
<script>
import { Navbar, TabItem,Indicator} from "mint-ui";
import hotheader from "src/components/allhot-header.vue";
import thubmUp from "src/components/thumb-up.vue";
import versioncofig from "src/components/common/versionconfig.vue";
import commentbody from "src/components/comment-detail-body.vue";
import ylheader from "src/components/yl-header.vue";
import api from "src/api/index";
import { mapState, mapMutations } from "vuex";

export default {
  name:"shuoshuo",
  data() {
    return {
      swiperIndex:0,
      popupVisible:false,
      popImg:'',
      selected: "1",
      commentlist: [],
      isshuoshuoempty:false,
      myid: "",
      pageone: 1,
      hasmore: "",
      pagetwo: 1,
      timeorhot: "",
      mypage: "",
      timelist: "",
      hotlist: "",
      loadmore: false,
      is_r: false,
      isRuleShow:false,//是否显示版规
      ruleConfig:null,//版规内容
    };
  },
  components: {
    Navbar,
    TabItem,
    hotheader,
    thubmUp,
    commentbody,
    ylheader,
    versioncofig
  },
  watch: {
    myid(val) {
      this.changesaystatus(val);
      this.myid = val;
    }
  },
  mounted() {
   Indicator.open("加载中...");
    this.selected = this.saystatus;
    this.myid = this.saystatus;
    this.init();
  },
  computed: {
    ...mapState(["saystatus","searchresultselected"])
  },
  methods: {
    ...mapMutations(["changesaystatus","changesearchresultselected"]),
        //显示图片
    popupImg(data,index){
      console.log(data,index)
      this.swiperIndex = index
      if(typeof data == 'string'){
        data = data.split(',')
      }
       //console.log(data,index)
      this.popImg = data;
      this.popupVisible = true;
      // console.log(this.swiperOne)
      // this.swiperOne.slideTo(index)
    },
    init() {
      this.initSay()
        .then(data => {
          return this.saysruledetail();
        })
        .then(data => {
          return this.initScroll();
        })
        .then(data => {
          this.$nextTick(() => {
            this.myscroll.refresh();
          });
          let loadmore = document.getElementsByClassName("loadmore-ul");
          if ("detail2say" == localStorage.turnCount) {
            if (loadmore.length > 0) {
              setTimeout(() => {
                loadmore[0].style.transform = localStorage.turnBackSay;
              }, 0);
            }
            localStorage.turnCount = "";
             Indicator.close();
          }
          this.myscroll.refresh();
        });
    },
    initSay() {
      let p = new Promise((resolve, reject) => {
        if (
          "index2say" == localStorage.turnCount ||
          "" == localStorage.turnCount
        ) {
           Indicator.close();
          if (this.myid == "1") {
            this.timeorhot = "0";
            this.mypage = this.pageone;
          } else if (this.myid == "2") {
            this.timeorhot = "1";
            this.mypage = this.pagetwo;
          }
          const data = {
            page: this.mypage,
            limit: 10,
            type: this.timeorhot
          };
          api.querySaysList(data).then(res => {
            if (res.success) {
             Indicator.close();
              resolve("获取得到数据...");
              this.commentlist = this.loadmore
                ? [...this.commentlist, ...res.data.list]
                : res.data.list; //res.data.list
              this.$util.getListUrl(this.commentlist);
              this.picAutoOrient(0);
              this.totalPage = res.data.totalPage;
              if (res.data.currPage == res.data.totalPage) {
                this.hasmore = false;
              } else {
                this.hasmore = true;
              }
              this.is_r = false;
              if (this.mypage > 1) {
                setTimeout(() => {
                  this.myscroll.refresh();
                }, 0);
              }

              let sayObj = JSON.stringify({
                commentlist: this.commentlist,
                totalPage: this.totalPage,
                hasmore: this.hasmore,
                pageone: this.pageone,
                pagetwo: this.pagetwo,
                mypage: this.mypage,
                timeorhot: this.timeorhot
              });
              localStorage.sayStorage = sayObj;
            } else {
              resolve("获取说说数据失败...");
            }
          });
        } else if ("detail2say" == localStorage.turnCount) {
           Indicator.close();
          let sayObj = JSON.parse(localStorage.sayStorage);
          this.commentlist = sayObj.commentlist;
          this.totalPage = sayObj.totalPage;
          this.hasmore = sayObj.hasmore;
          this.is_r = false;
          this.pageone = sayObj.pageone;
          this.pagetwo = sayObj.pagetwo;
          this.mypage = sayObj.mypage;
          this.timeorhot = sayObj.timeorhot;
          resolve(true);
        }
      });
      return p;
    },
    initScroll() {
      let p = new Promise((resolve, reject) => {
        let sayWrapper = this.$refs.sayWrapper;
        this.$nextTick(() => {
          this.setScroll(sayWrapper, this);
          resolve("初始化scroll结束...");
        });
      });
      return p;
    },
    setScroll(sayWrapper, _this) {
      localStorage.tempPageHeight = document.getElementsByClassName(
        "loadmore-ul"
      )[0].scrollHeight;
      _this.myscroll = new iScroll(sayWrapper, {
        //上拉时触发
        onScrollMove: function() {
          if (
            this.y <= this.wrapperH - this.scroller.clientHeight - 50 &&
            _this.is_r == false
          ) {
            //加载数据
            _this.is_r = true;
            _this.loadmore = true;
            if (_this.mypage < _this.totalPage) {
              if (_this.timeorhot == "0") {
                _this.pageone += 1;
                _this.getsayslist();
              } else if ((_this.timeorhot = "1")) {
                _this.pagetwo += 1;
                _this.getsayslist();
              }
            }
          }
        },
        onScrollEnd: function() { },
        onScrollStart: function() {
          if (localStorage.tempPageHeight != document.getElementsByClassName("loadmore-ul")[0].scrollHeight) {
            this.refresh();
            localStorage.tempPageHeight = document.getElementsByClassName(
              "loadmore-ul"
            )[0].scrollHeight;
          }
        }
      });
      Indicator.close();
    },
    getsayslist() {
      if (this.myid == "1") {
        this.timeorhot = "0";
        this.mypage = this.pageone;
      } else if (this.myid == "2") {
        this.timeorhot = "1";
        this.mypage = this.pagetwo;
      }
      const data = {
        page: this.mypage,
        limit: 10,
        order: "desc",
        type: this.timeorhot
      };
      api.querySaysList(data).then(res => {
        if (res.success) {
          this.commentlist = this.loadmore
            ? [...this.commentlist, ...res.data.list]
            : res.data.list; //res.data.list
            if(this.commentlist==''){
                  this.isshuoshuoempty=true
            }else{
                  this.isshuoshuoempty=false
            }
          this.picAutoOrient(this.mypage - 1);
          this.$util.getListUrl(this.commentlist);
          this.totalPage = res.data.totalPage;
          if (res.data.currPage == res.data.totalPage) {
            this.hasmore = false;
          } else {
            this.hasmore = true;
          }
          this.is_r = false;
          if (this.mypage > 1) {
            setTimeout(() => {
              this.myscroll.refresh();
            }, 0);
          }

          let sayObj = JSON.stringify({
            commentlist: this.commentlist,
            totalPage: this.totalPage,
            hasmore: this.hasmore,
            pageone: this.pageone,
            pagetwo: this.pagetwo,
            mypage: this.mypage,
            timeorhot: this.timeorhot
          });
          localStorage.sayStorage = sayObj;
        }
      });
    },
    sayssearch() {
      this.changesearchresultselected(0);
      this.$router.push({ path: "/search", query: { type: "2" } });
    },
    saythumbup(data) {
      const params = {
        saysId: this.commentlist[data.commentindex].saysId,
        createSaysUserId: this.commentlist[data.commentindex].userId
      };
      if (this.commentlist[data.commentindex].isgood == 0) {
        api.Querysaythumbup(params).then(res => {
          if (res.success) {
            this.$util.saveFootPrint({actType:9,typeValue:this.commentlist[data.commentindex].saysId});//用户轨迹
            this.commentlist[data.commentindex].isgood = 1;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
          } else {
            this.$toast("点赞失败");
          }
        });
      } else if (this.commentlist[data.commentindex].isgood == 1) {
        api.Querysaycanclethumbup(params).then(res => {
          if (res.success) {
            this.commentlist[data.commentindex].isgood = 0;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
          } else {
            this.$toast("取消点赞失败");
          }
        });
      }
    },
    saycomment(data) {
      localStorage.turnCount = "detail2say";
      this.getTransformState();
      this.$router.push({
        path: "/shuodetail",
        query: {
          saysId: this.commentlist[data.commentindex].saysId,
          shuoshuoIndex: data.commentindex
        }
      });
    },
    addshuoshuo() {
      this.$router.push({ path:"/publishbigsay",query:{tag:0}})
    },
    saynew() {
      if(this.myscroll){
        this.myscroll.destroy();
      }
      this.commentlist = "";
      this.pageone = 1;
      this.myid = "1";
      this.selected = "1";
      localStorage.turnCount = "";
      this.init();
    },
    sayhot() {
      if(this.myscroll){
        this.myscroll.destroy();
      }
      this.commentlist = "";
      this.pagetwo = 1;
      this.myid = "2";
      this.selected = "2";
      localStorage.turnCount = "";
      this.init();
    },
    tosaycomdet(data) {
      localStorage.turnCount = "detail2say";
      this.getTransformState();

      this.$router.push({
        path: "/shuodetail",
        query: {
          saysId: this.commentlist[data.commentindex].saysId,
          userId: this.commentlist[data.commentindex].userId,
          shuoshuoIndex: data.commentindex
        }
      });
    },
    //获取跳转前的位置
    getTransformState() {
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if (loadmore.length > 0) {
        localStorage.turnBackSay = loadmore[0].style.transform;
      }
    },
    //图片自动旋转参数
    picAutoOrient(data) {
      for (var m = 10 * data; m < this.commentlist.length; m++) {
        for (var n = 0; n < this.commentlist[m].picture.length; n++) {
          this.commentlist[m].picture[n].src =
            this.commentlist[m].picture[n].src + "?imageMogr2/auto-orient";
        }
      }
    },
    saysruledetail(){//查询说说版规
      let p = new Promise((resolve, reject) => {
        api.saysruledetail().then(res=>{
          if(res.success){
            this.ruleConfig=res.config;
            if(res.config){
              this.isRuleShow=true
            }else{
              this.isRuleShow=false
            }
          }
          resolve("获取说说版规...");
        })
      })
      return p;
    }
  },
  destroyed() {
    this.myscroll.destroy();
  }
};
</script>
<style lang="less">
.modal-img{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  position: fixed;
  top:0;
  left: 0;
  z-index: 9999;
  img{
    width: 80%;
    position: absolute;
    top:50%;
    left: 10%;
    transform: translateY(-50%);
  }
}
.shuoshuo-mtnav {
  border-bottom: 1px solid #e6e6e6;
  padding: 0 1.46rem 0 1.46rem;
  justify-content: space-between;
  height: 0.9rem;
  .mint-tab-item-label {
    line-height: 0.2rem;
    font-size: 0.3rem;
    font-family: "PingFangSC Regular";
  }
  .mint-tab-item {
    color: #494949;
    width: 1rem;
    flex: inherit;
  }
  .mint-tab-item.is-selected {
    color: #fb685b;
    width: 1rem;
    border-bottom: 0.02rem solid #fb685b;
  }
  .mint-tab-item.is-selected {
    margin-bottom: 0;
  }
}

.shuoshuo-navbar-sep {
  background-color: #e6e6e6;
  width: 1px;
  height: 0.5rem;
  position: fixed;
  left: 3.745rem;
  top: 1.08rem;
  z-index: 2;
}

.shuoshuo-new {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 11.56rem;
  padding: 0 1rem;
}

.nosvg {
  font-size: 1.66rem;
  margin-top: 3.1rem;
  color: #999999;
}

.no-text {
  font-size: 0.3rem;
  color: #999999;
  font-family: "PingFangSC Regular";
  text-align: center;
  margin-top: 0.4rem;
}
</style>
<style lang="less" scoped>
.loadmore-container {
  height: 95vh;
  overflow: auto !important;
  margin: 0 auto;
}

.loadmore-ul {
  padding-bottom: 1.2rem;
  list-style: none;
}

</style>
